<?php

namespace app\api\controller\worker;

use app\api\controller\Base;
use app\common\model\AdminModel;
use app\common\model\base\DictItemModel;
use app\common\model\node\NodeModel;
use app\common\model\node\NodeProcessModel;
use app\common\model\worker\CustomerAuthModel;
use app\common\model\worker\CustomerModel;
use app\common\model\worker\CustomerPaymentModel;
use app\common\model\worker\OfferModel;
use app\common\model\worker\TaskModel;
use think\facade\Db;
use think\facade\View;
use think\Request;

class CustomerPaymentController extends Base
{

    private $model;
    private $customerModel;
    private $nodeModel;
    private $taskModel;
    private $adminModel;
    /**
     * 构造方法
     * @access public
     * @throws \Exception
     */
    public function __construct()
    {

        parent::__construct();
        $this->checkLogin();
        $this->model = new CustomerPaymentModel();
        $this->customerModel = new CustomerModel();
        $this->nodeModel = new NodeModel();
        $this->taskModel = new TaskModel();
        $this->adminModel = new AdminModel();

    }

    /**
     * 财务列表
     */
    public function index()
    {
        $pageSize      = $this->request->param('pageSize/d', 20); //每页多少条
        $pageNumber    = $this->request->param('pageNumber/d'); //当前页
        $sortName      = $this->request->param('sortName'); //排序字段
        $sortOrder     = $this->request->param('sortOrder', 'desc'); //升序降序
        $order         = !empty($sortName) ? "{$sortName} {$sortOrder}" : ''; //排序
        $keyword = $this->request->param('keyword');
        $map = [];
        $searchData    = $this->getSearchData();
        $data          = ['total' => 0, 'rows' => []];
        $data['total'] = $this->model->withSearch('filter', $searchData)->count();
        if ($data['total'] > 0) {
            $rows = $this->model->withSearch('filter', $searchData)
                ->where($map)
                ->page($pageNumber, $pageSize)
                ->order($order)
                ->select()
                ->toArray();
            $rows = $this->model->_formatList($rows);
            $data['rows'] = $rows;
        }
        $this->result($data);
    }

    public function payment(){
        $data = $this->request->param();
        $this->validate($data,[
            'customer_id|客户'=>'require',
            'pay_amount|金额'=>'require|float',
            'pay_type|支付方式'=>'require',
            'is_pay|收支类型'=>'require',
        ]);
        $data['action_admin_id'] = $this->loginInfo['id'];
        $info = $this->model->add($data);
        $this->success('','',$info);
    }

    /**
     * @author bxm
     * @date 2022-06-21 15:37
     * 收款
     */
    public function paymentAdd(){
        $roles_ids = $this->role_ids;
        if(!in_array(7,$roles_ids)){

            $this->result([],'该用户没有权限，只有业务员有操作权限！',0);
        }
        $param = $this->request->param();

        if($param['is_pay'] == 1){
            $rule = [
                'is_pay|方式'=>'require', //1收款 -1退款
                'customer_id|客户'=>'require',
                'pay_amount|收款金额'=>'require|float',
                'payment_id|支付方式id'=>'require',
                'receipt_imgs|收据'=>'require',
                'voucher_imgs|收款凭证'=>'require',
            ];
            $payment_id = $param['payment_id'];

            $this->validate($param,$rule);
            $data['action_admin_id'] = $this->loginInfo['id'];
            $DictItemModel = new DictItemModel();
            $pay_type = $DictItemModel->where('class_code','10.04')->where('dict_code',$payment_id)
                ->value('dict_value');
            $data['pay_type'] = $pay_type;
            $data['payment_id'] = $payment_id;
            $data['receipt_imgs'] = json_encode($param['receipt_imgs'],JSON_UNESCAPED_UNICODE);
            $data['voucher_imgs'] = json_encode($param['voucher_imgs'],JSON_UNESCAPED_UNICODE);
            $data['pay_remark'] = $param['pay_remark'] ?? '';
            $data['pay_amount'] = $param['pay_amount'];
            $data['is_pay'] = $param['is_pay'];
            $data['customer_id'] = $param['customer_id'];

        }else{
            $rule = [
                'is_pay|方式'=>'require', //1收款 -1退款
                'customer_id|客户'=>'require',
                'pay_amount|退款金额'=>'require|float',
                'account_name|退款户名'=>'require',
                'account_number|退款账号'=>'require',
                'bank_name|银行'=>'require',
                'open_bank|开户行'=>'require',
                'pay_remark|退款备注'=>'require',
            ];
            $this->validate($param,$rule);
            $data = [
                'is_pay' => -1,
                'customer_id' => $param['customer_id'],
                'pay_amount' =>$param['pay_amount'],
                'action_admin_id'=>$this->loginInfo['id'],
                'account_name'=>$param['account_name'],
                'account_number'=>$param['account_number'],
                'bank_name'=>$param['bank_name'],
                'open_bank'=>$param['open_bank'],
                'pay_remark'=>$param['pay_remark'],
                'action_admin_id' =>$this->loginInfo['id'],
            ];

        }
        $amount = $data['pay_amount']*$data['is_pay'];
        if($amount==0) exception('支付金额不能为零');
        if($amount<0){
            $payAmount = CustomerModel::where('id',$data['customer_id'])->value('payment_amount');
            if($payAmount<$data['pay_amount'])
            {
                $this->result([],'退金额大于客户支付金额',0);
            }
        }

        $info = $this->model->add($data);
        //添加收款任务
        if($param['is_pay'] == 1){
            $nodeProcess = NodeProcessModel::where('node_id', 11)->find();
            $nodeInfo = NodeModel::where('id',11)->find();
            if(empty($nodeInfo)){
                $this->result([],'任务配置已被修改',0);
            }
            $node_id = 11;
        }else{
            $nodeProcess = NodeProcessModel::where('node_id', 12)->order('id', 'asc')->find();
            $nodeInfo = NodeModel::where('id',12)->find();
            if(empty($nodeInfo))
            {
                $this->result([],'任务配置已被修改',0);
            }

            $node_id = 12;
        }


        //添加到任务里
        $dataTask = [
            'customer_id' => $data['customer_id'],
            'order_id' => 0,
            'node_id' => $node_id,
            'process_id' => $nodeProcess['id'],
            'receive_admin_id' => $nodeProcess['audit_admin_id'],
            'action_table_id'=>$info['id'],//操作表id
            'admin_id'=>$this->loginInfo['id']
        ];
        $this->taskModel->commonAddTask($dataTask);
        //任务通知
        $this->taskModel->sendTaskInfo($dataTask['receive_admin_id'],$nodeProcess['process_name']);
        $this->result($info,'操作成功',1);
    }

    public function List(){
        $pageSize      = $this->request->param('pageSize/d', 20); //每页多少条
        $pageNumber    = $this->request->param('pageNumber/d') ?? 1; //当前页
        $sortName      = $this->request->param('sortName'); //排序字段
        $sortOrder     = $this->request->param('sortOrder', 'desc'); //升序降序
        $param = $this->request->param();
        $rule = [
            'customer_id|客户'=>'require',
        ];
        $this->validate($param,$rule);
        $list = $this->model->alias('cal')
            ->leftJoin('admin a', 'a.id = cal.action_admin_id')
            ->where('cal.customer_id',$param['customer_id'])
            ->order('cal.id','desc')
            ->field('a.nickname,cal.*')
             ->paginate(['list_rows'=> $pageSize, 'page' => $pageNumber]);

        $this->result($list,'操作成功',1);


    }
    public function getInfo(Request $request)
    {
        $param = $request->param();
        //开始校验
        $this->validate($param, [
            'id|记录id' => 'require',
        ]);
        $id = $param['id'];
        $list = $this->model->alias('cal')->leftJoin('admin a', 'a.id = cal.action_admin_id')
            ->where('cal.id', $id)
            ->field('a.nickname,cal.*')
            ->find();
        $this->result($list, '操作成功', 1);
    }




}
